package com.tdam2013.grupo07.servicios;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.tdam2013.grupo07.R;
import com.tdam2013.grupo07.data.DatabaseHelper;
import com.tdam2013.grupo07.data.DatabaseHelperSingleton;
import com.tdam2013.grupo07.mensajes.ChatMensaje;
import com.tdam2013.grupo07.networking.MessageDispatcherSingleton;
import com.tdam2013.grupo07.networking.QueryMessagesEventObserver;
import com.tdam2013.grupo07.networking.QueryMessagesResponse;
import com.tdam2013.grupo07.networking.ServerConectivity;
import com.tdam2013.grupo07.networking.ServerConectivitySingleton;

public class ServicioMensajeria extends IntentService implements QueryMessagesEventObserver
{
	public ServicioMensajeria() {
		super("ServicioMensajeria");
	}
	private static final int ACTIVE_SERVICE_ID = 1;
	private long timestampFrom;
	
	@Override
	protected void onHandleIntent(Intent intent) {
		super.onStart(intent, ACTIVE_SERVICE_ID);
		ServerConectivity serverConectivity=ServerConectivitySingleton.getInstance(getApplicationContext()).getServerConectivity();
		serverConectivity.addQueryMessagesObserver(this);
		
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String user=preferences.getString(getResources().getString(R.string.activity_ajustes_usuario_key), null);
		
		DatabaseHelper dbHelper=DatabaseHelperSingleton.getInstance(getApplicationContext()).getDatabaseHelper();
		timestampFrom=dbHelper.seleccionarFechaUltimoMensajeRecibido()+1000l;
		String newUser=null;
		String password=null;
		SimpleDateFormat formatter= new SimpleDateFormat(getResources().getString(R.string.server_date_time_format));
		while(true)
		{
			if(user!=null && password != null)
			{
				newUser=preferences.getString(getResources().getString(R.string.activity_ajustes_usuario_key), null);
				if(user!=null && newUser!=null && !newUser.equalsIgnoreCase(user))
				{
					user=newUser;
					password=preferences.getString(getResources().getString(R.string.activity_ajustes_password_key), null);
				}
				serverConectivity.queryMessagesAsync(user, password, formatter.format(new Date(timestampFrom)));
			}
			else
			{
				user=preferences.getString(getResources().getString(R.string.activity_ajustes_usuario_key), null);
				password=preferences.getString(getResources().getString(R.string.activity_ajustes_password_key), null);
			}
			try {
				Thread.sleep(60000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}	
	}
		
		@Override
		public void updateQueryMessages(QueryMessagesResponse response) 
		{
			if(response.isSuccess())
			{
				List<ChatMensaje> messages=response.getMessages();
				Collections.sort(messages);
				if(!messages.isEmpty())
					timestampFrom=messages.get(messages.size()-1).getFecha().getTime()+1000l;
				DatabaseHelper dbHelper=DatabaseHelperSingleton.getInstance(getApplicationContext()).getDatabaseHelper();
				for(ChatMensaje message: messages)
				{
					message.setId(dbHelper.insertarMensaje(message.getDestinatario(), response.getUser(), message.getFecha().getTime(), message.getTipo(), message.getTexto()));
				}
				MessageDispatcherSingleton.getInstance().recieveMessages(messages);
			}
		}
	}
